import Taro from '@tarojs/taro';
import { logInfo, toast } from '@/utils/tools';
import { pageToLogin } from './utils';
// import interceptors from './interceptors';

//添加拦截器
// interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem));

//网络请求拦截器
const interceptor = function(chain) {
  const requestParams = chain.requestParams;
  // const { method, data, url } = requestParams
  const token = Taro.getStorageSync('token'); //拿到本地缓存中存的token
  logInfo('token:', token);
  const cookies = Taro.getStorageSync('cookies');
  const custToken = Taro.getStorageSync('custToken');
  if (token) {
    requestParams.header = {
      ...requestParams.header,
      Authorization: `Bearer ${token}`, //将token添加到头部
    };
  }
  if (cookies) {
    requestParams.header = {
      ...requestParams.header,
      cookie: cookies,
    };
  }
  if (custToken) {
    requestParams.header = {
      ...requestParams.header,
      custToken,
    };
  }
  return chain.proceed(requestParams).then((res) => res);
};

Taro.addInterceptor(interceptor);

let timer: any = null;
const throttle = (_str, opeFun?) => {
  //str为提示语
  if (!timer) {
    timer = setTimeout(() => {
      if (opeFun) opeFun();
      else {
        // Taro.atMessage({
        //   message: str,
        //   type: 'info',
        // });
        toast(_str);
      }
      timer = null;
    }, 1000);
  }
};

const request = async(method, url, params, showLoading = false) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  if (showLoading) {
    await Taro.showLoading({
      title: '加载中',
    });
  }
  let contentType = params?.data
    ? 'application/json'
    : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  logInfo('参数：', params && (params?.data || params?.params));
  const option = {
    method,
    isShowLoading: false,
    url: BASE_URL + url,
    data: params && (params?.data || params?.params),
    timeout: 50000, // 超时时间
    header: {
      'content-type': contentType,
    },
    success(res) {
      logInfo(url, res);
      Taro.hideLoading();
      //根据不同返回状态值3进行操作
      switch (res?.statusCode) {
        case 503: {
          break;
        }
        case 404: {
          // pageTo404();
          throttle('请求资源不存在');
          break;
        }
        case 401: {
          throttle('', () => {
            // 跳转登录页
            pageToLogin();
          });
          break;
        }
        case 200: {
          switch (res.data?.code) {
            case 401: {
              if (url === '/portal/app/message/swiper') {
                // 工作台消息轮询401暂时不重定向登录页（场景-扫码需求）
              } else {
                throttle('', () => {
                  // 跳转登录页
                  pageToLogin();
                });
              }
              break;
            }
            case 200:
              if (res?.cookies && res.cookies.length > 0) {
                const cookies = res.cookies.toString();
                Taro.setStorageSync('cookies', cookies);
              }
              break;
            default:
              throttle(res?.data.msg);
              break;
          }
          break;
        }
        default:
          break;
      }
    },
    error(e) {
      Taro.hideLoading();
      logInfo(url, e);
      throttle(e.message);
    },
  };
  const resp = await Taro.request(option);
  return resp.data; //根据个人需要返回
};

export default {
  get: (url, config, showLoading?) => request('GET', url, config, showLoading),
  post: (url, config, showLoading) => request('POST', url, config, showLoading),
  put: (url, config, showLoading) => request('PUT', url, config, showLoading),
  delete: (url, config, showLoading) => request('DELETE', url, config, showLoading),
  patch: (url, config, showLoading) => request('PATCH', url, config, showLoading),
};
